package com.asiainfo.dacp.datastash.broker.workerctrl;

import com.asiainfo.dacp.datastash.broker.core.BrokerContext;
import com.asiainfo.dacp.datastash.broker.core.vo.StashUnitTask;
import com.asiainfo.dacp.datastash.broker.facade.UnitTaskFacade;
import com.asiainfo.dacp.datastash.broker.facade.state.UnitTaskStateLogService;
import com.asiainfo.dacp.datastash.broker.tracelog.StashTraceLogVo;
import com.asiainfo.dacp.datastash.broker.tracelog.StashTraceLogger;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecuteResultHandler;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.PumpStreamHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;

/**
 * stashUnit的执行器类
 * 加载需要执行的参数，构建成本地命令，完成进程的fork
 *
 * 能对fork的进程的管理，挂起，恢复，中止
 *
 * @author MeiKefu
 * @date 2017-10-31
 */
@Service
public class StashWorkExecutor {

    @Autowired
    private StashTraceLogger tracelog;
    private String clzName = this.getClass().getSimpleName();

    @Autowired
    private UnitTaskFacade unitTaskFacade;

    public void execute(StashUnitTask stashUnitTask){

        unitTaskFacade.taskProcess(stashUnitTask);

        String line = "java";
        CommandLine cmdLine = CommandLine.parse(line);
        cmdLine.addArguments(new String[]{"-version"});
        DefaultExecutor executor = new DefaultExecutor();

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        executor.setStreamHandler(streamHandler);
        executor.setExitValue(0);
        //非阻塞
        DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
        try {
            executor.execute(cmdLine,resultHandler);
            resultHandler.waitFor();
            complete(stashUnitTask);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void complete(StashUnitTask stashUnitTask){

        unitTaskFacade.taskComplete(stashUnitTask);
        //TDOD 更新队列状态，判断是否最后一个，完成整个unit的更新

    }

}
